第一个 go web 程序

第一个 go web 程序

package main

import (
	"fmt"
	"net/http"
)
func welcome (w http.ResponseWriter,r *http.Request){
	// 设置响应头
	w.Header().Set("Content-Type","text/html;charset=utf-8")
	fmt.Fprintln(w,"服务器返回的信息<b>加粗</b>")
}
func main() {
	// 如果访问/abc路径,交给welcome方法去处理
	http.HandleFunc("/abc",welcome)
	// 监听本机8081端口
	http.ListenAndServe("localhost:8081",nil)
}

单控制器

package main

import (
	"net/http"
)
type MyHander struct{

}
func (m *MyHander) ServeHTTP(w http.ResponseWriter,r *http.Request ){
	w.Write([]byte("返回的数据"))
}
func main() {
	h := MyHander{}
	server := http.Server{Addr:"localhost:8090",Handler:&h}
	server.ListenAndServe()
}

多控制器

1、多处理器实现

package main

import (
	"net/http"
)
type MyHander struct{

}
type MyHande struct{

}
func (m *MyHande) ServeHTTP(w http.ResponseWriter,r *http.Request ){
	w.Write([]byte("返回的数据two"))
}
func (m *MyHander) ServeHTTP(w http.ResponseWriter,r *http.Request ){
	w.Write([]byte("返回的数据"))
}
func main() {
	h := MyHander{}
	h2 := MyHande{}
	//server := http.Server{Addr:"localhost:8090",Handler:&h}
	server := http.Server{Addr:"localhost:8090"}
	http.Handle("/first",&h)
	http.Handle("/second",&h2)
	server.ListenAndServe()
}

2、多函数实现

package main

import (
	"fmt"
	"net/http"
)
func first(w http.ResponseWriter,r *http.Request){
	fmt.Fprintln(w,"多函数-first")
}
func second(w http.ResponseWriter,r *http.Request){
	fmt.Fprintln(w,"多函数-second")
}
func main(){
	server:=http.Server{Addr:"localhost:8090"}
	http.HandleFunc("/first",first)
	http.HandleFunc("/second",second)
	server.ListenAndServe()
}

在这里插入图片描述

发布了117 篇原创文章 · 获赞 222 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43901693/article/details/101121937