golang http-server demo

本文演示了如何使用Golang的`net/http`包快速创建一个HTTP服务器,监听9090端口。服务器设置了一个路由`/foo`,当客户端请求时,将读取并返回`test.html`的内容。`test.html`包含了HTML代码,包括一个红色标题、百度链接、图片和一个按钮。当点击按钮时,JavaScript会改变图片的源URL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Golang is so easy to create http-server, just use package “net/http”.
ListeAndServe start listen a port, if client have request, HandleFunc registry path and point to a function

package main

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

func foo(w http.ResponseWriter, r *http.Request) {
	file, err := ioutil.ReadFile("./test.html")
	if err != nil {
		w.Write([]byte(fmt.Sprintf("%v", err)))
	}
	w.Write(file)
}

func main() {
	http.HandleFunc("/foo", foo)
	http.ListenAndServe("0.0.0.0:9090", nil)
}

We can wirte html code in test.html

<h1 style="color:red">bar</h1>
<a href="https://www.baidu.com">点我去百度</a>
<img id="i1" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602760046007&di=620d28f5f0592db0fd175c3f923f27ab&imgtype=0&src=http%3A%2F%2Fimg1.cache.netease.com%2Fcatchpic%2FE%2FE5%2FE5DD0A8099E2D28226465C6894F7A7A1.jpg">
<button id="b1">点我</button>
<script>
    document.getElementById("b1").onclick=function () {
        document.getElementById("i1").src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3035184011,4060465026&fm=26&gp=0.jpg"
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值