Go 语言:使用 http 包构建 HTTP 服务


#Go 语言#


示例1

package main

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

func indexHandler(respWriter http.ResponseWriter, r *http.Request) {
	_, _ = fmt.Fprintf(respWriter, "Hello")
}

func main() {
	http.HandleFunc("/", indexHandler)
	_ = http.ListenAndServe(":8000", nil)
}

运行后,浏览器访问http://127.0.0.1:8000/,会展示 Hello

示例2

package main

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

func indexHandler(respWriter http.ResponseWriter, r *http.Request) {
	_, _ = fmt.Fprintf(respWriter, "Hello")
}

func welcomeHandler(respWriter http.ResponseWriter, r *http.Request) {
	_, _ = fmt.Fprintf(respWriter, "Welcome")
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/welcome", welcomeHandler)
	_ = http.ListenAndServe("127.0.0.1:8000", nil)
}

运行后,浏览器访问http://127.0.0.1:8000/http://127.0.0.1:8000/wel等网址,会展示 Hello

浏览器访问http://127.0.0.1:8000/welcome,会展示 Welcome

示例3:

package main

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


type simpleHandler struct {
	content string
}

func (ih *simpleHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, ih.content)
}


func main() {
	http.Handle("/", &simpleHandler{content:"Hello"})
	http.Handle("/welcome", &simpleHandler{content:"Welcome"})
	_ = http.ListenAndServe("127.0.0.1:8000", nil)
}

运行后,浏览器访问http://127.0.0.1:8000/http://127.0.0.1:8000/wel等网址,会展示 Hello

浏览器访问http://127.0.0.1:8000/welcome,会展示 Welcome

示例4

package main

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


type simpleHandler struct {
	content string
}

func (ih *simpleHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, ih.content)
}


func main() {
	mux := http.NewServeMux()
	mux.Handle("/", &simpleHandler{content:"Hello"})
	mux.Handle("/welcome", &simpleHandler{content:"Welcome"})

	http.ListenAndServe("127.0.0.1:8000", mux)
}

运行后,浏览器访问http://127.0.0.1:8000/http://127.0.0.1:8000/wel等网址,会展示 Hello

浏览器访问http://127.0.0.1:8000/welcome,会展示 Welcome


( 本文完 )