美文网首页深入浅出golangGolang 入门资料+笔记Golang
61. HTTP处理类型自定义ServeHTTP方法

61. HTTP处理类型自定义ServeHTTP方法

作者: 厚土火焱 | 来源:发表于2017-10-19 11:26 被阅读92次

在 go 语言中,我们可以给类型增加自定义的方法。下面实验增加ServeHTTP方法。
首先建立两个类型

type String string

type Struct struct {
    Greeting    string
    Punct       string
    Who         string
}

给类型增加 ServeHTTP 方法

func (s String)ServeHTTP(w http.ResponseWriter, r *http.Request)  {
    fmt.Fprint(w, s)
}

func (s Struct)ServeHTTP(w http.ResponseWriter, r *http.Request)  {
    fmt.Fprint(w, s)
}

在 ServeHTTP 前的括号内,就是要增加方法的类型。
在 主函数 main 中写相关的监听。我们定义为使用 4000 端口。

    http.Handle("/string", String("I'm a Gopher"))
    http.Handle("/struct", &Struct{"Hello", ":", "Gopher!"})
    log.Fatal(http.ListenAndServe(":4000", nil))

系统运行后,使用浏览器查看运行效果


string路径 struct路径

完整代码

/**
* myHttp
* @Author:  Jian Junbo
* @Email:   junbojian@qq.com
* @Create:  2017/10/19 10:35
* Copyright (c) 2017 Jian Junbo All rights reserved.
*
* Description:  
*/
package main

import (
    "net/http"
    "fmt"
    "log"
)

type String string

type Struct struct {
    Greeting    string
    Punct       string
    Who         string
}

func (s String)ServeHTTP(w http.ResponseWriter, r *http.Request)  {
    fmt.Fprint(w, s)
}

func (s Struct)ServeHTTP(w http.ResponseWriter, r *http.Request)  {
    fmt.Fprint(w, s)
}

func main() {
    http.Handle("/string", String("I'm a Gopher"))
    http.Handle("/struct", &Struct{"Hello", ":", "Gopher!"})
    log.Fatal(http.ListenAndServe(":4000", nil))
}

相关文章

网友评论

    本文标题:61. HTTP处理类型自定义ServeHTTP方法

    本文链接:https://www.haomeiwen.com/subject/mjluuxtx.html