基于Golang的Web服务(http协议)

1. http服务端代码

package http

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

// 封装接口返回结构体
type result struct {
	Status bool
	Code int
	Data interface{}
}

// w表示response对象,返回给客户端的内容都在对象里处理
// r表示客户端请求对象,包含了请求头,请求参数等等
func index(w http.ResponseWriter, r *http.Request) {
	// 往w里写入内容,就会在浏览器里输出
	fmt.Fprintf(w, "server action")
}

// post 请求
func add(w http.ResponseWriter, r *http.Request) {
	// 获取客户端POST方式传递的参数
	body, _ := ioutil.ReadAll(r.Body)
	fmt.Println(string(body))

	// 向客户端返回JSON数据
	data := make(map[string]interface{})
	data["param1"] = "result1"
	data["param2"] = "result2"

	// 按接口约定返回
	result := result{Status: true, Code: 0, Data: data}

	w.Header().Set("Content-Type", "application/json")
	json, _ := json.Marshal(result)
	w.Write(json)
}

// main函数调用即可启动服务
func Server()  {
	// 设置路由,如果访问/,则调用index方法
	http.HandleFunc("/", index)

	http.HandleFunc("/api/add", add)

	// 启动web服务,监听9090端口
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

 

2. 启动http服务

package main

import "github.com/15902124763/go-base/http"

func main()  {
	// 启动http服务
	http.Server()
}

 

3.代码地址(在http文件夹下的server.go文件)

https://github.com/15902124763/go-base

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值