You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang运行报syntax error: unexpected newline语法错误求助

错误原因

你遇到的语法错误由代码大括号未正确闭合、路由注册逻辑嵌套错误导致,具体问题如下:

  • 第一个/路径的http.HandleFunc传入的匿名函数写完逻辑后,缺少闭合的}和函数调用结束的)
  • 第二个/membuat-web-dengan-golang路径的http.HandleFunc传入的匿名函数同样缺少闭合的}和函数调用结束的)
  • 你误将第二个路由注册、静态资源注册、服务启动的逻辑全部写进了第一个路由的匿名函数内部,语法层级完全错误

修正后代码

package main

import "fmt"
import "net/http"
import "html/template"
import "path"

func main() {
    // 根路径路由
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        var filepath = path.Join("index.html")
        var tmpl, err = template.ParseFiles(filepath)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        // 模板渲染逻辑,原代码缺失该步骤
        tmpl.Execute(w, nil)
    })

    // 业务路由
    http.HandleFunc("/membuat-web-dengan-golang", func(w http.ResponseWriter, r *http.Request) {
        var filepath = path.Join("membuat-web-dengan-golang.html")
        var tmpl, err = template.ParseFiles(filepath)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        tmpl.Execute(w, nil)
    })

    // 静态资源路由
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("assets"))))

    fmt.Println("server started at localhost:9000")
    http.ListenAndServe(":9000", nil)
}

额外说明:原代码的两个路由处理函数仅做了模板解析,没有调用渲染方法,修正代码补充了该部分逻辑,避免接口返回空响应

内容的提问来源于stack exchange,提问作者shogun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:18:04