服务端相应流程和http标准库的基本使用

首选需要引入http标准库包

import "net/http"

基本代码:

func handlerFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>")
}

func main() {
    http.HandleFunc("/", handlerFunc)
    // 开启服务,并监听对应端口
    http.ListenAndServe(":3000", nil)
}

http.ResponseWriter 是返回客户端请求的

// http.ResponseWriter 使用方法
w.Header().Set("Trailer", "AtEnd1, AtEnd2") // 设置信息到标头
w.Header().Add("Trailer", "AtEnd3") //追加信息到标头,相同的key会新起一行
// 默认返回的是 text/plain 文本类型,需要设置成text/html网页标签才能生效
w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
w.WriteHeader(http.StatusOK) // 返回http状态码

http.Request 是客户端的请求信息

r.URL.Path //请求路径,可以依据这个判断路由显示页面

基本代码

package main
import (
    "fmt"
    "net/http"
)
func handlerFunc(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    if r.URL.Path == "/" {
        fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>")
    } else if r.URL.Path == "/about" {
        fmt.Fprint(w, "此博客是用以记录编程笔记,请联系 "+
            "<a href=\"mailto:ample.com\">summer@example.com</a>")
    } else {
        w.WriteHeader(http.StatusNotFound)
        fmt.Fprint(w, "<h1> 请求页面未找到 :( </h1>"+
            "<p> 如有疑惑,请联系我们。 </p>")
    }
}
func main() {
    http.HandleFunc("/", handlerFunc)
    http.ListenAndServe(":3000", nil)
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!