一文搞懂Go快速搭建HTTP服务

阅读 66

2022-05-24


第一个http程序:Hello World

package main

import "net/http"

//最简单的HTTP服务
func RunHttp1() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello Http!"))
})
http.ListenAndServe(":8080", nil)
}

func main() {
RunHttp1()
}

PostMan测试:

一文搞懂Go快速搭建HTTP服务_golang

一般请求

一般参数请求:

package main

import (
"fmt"
"net/http"
)

func GetMethod1() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//获取参数
str := r.URL.Query().Get("str")
fmt.Println("Get Method Str is " + str)
w.Write([]byte("Hello Http Get!"))
})
http.ListenAndServe(":8080", nil)
}


func main() {
GetMethod1()
}

测试:

一文搞懂Go快速搭建HTTP服务_http_02

表单请求

package main

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

type Student struct {
Name string
Age int
}

func GetMethod2() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//获取参数
name := r.URL.Query().Get("name")
age := r.URL.Query().Get("age")
//将string类型转为int类型
ageStr, err := strconv.Atoi(age)
if err != nil {
fmt.Println("err...")
}
stu := Student{Name: name, Age: ageStr}
fmt.Println("Get Method Str is ", stu)
w.Write([]byte("Hello Http Get Form!"))
})
http.ListenAndServe(":8080", nil)
}

func main() {
GetMethod2()
}

JSON格式的HTTP报文

package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)

//自定义结构体 对应JSON结构体
type Student struct {
Id int64 `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}

func TakeJSON() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//获取请求方法
fmt.Println("req method : ", r.Method)
//获取请求题
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("获取请求体错误 , %v\n", err)
return
}
fmt.Println("请求体 :", string(body))
//将请求的JSON转化为结构体
var stu Student
if err = json.Unmarshal(body, &stu); err != nil {
fmt.Printf("反序列化失败 , %v\n", err)
return
}
fmt.Printf("反序列化成功,JSON解析结果 %+v", stu)
w.Write([]byte("Hello Http Get Form!"))
})
http.ListenAndServe(":8080", nil)
}

func main() {
TakeJSON()
}




精彩评论(0)

0 0 举报