Gothic Framework G symbol

HTTP & Files

Fetch makes HTTP requests straight from your WASM component. GetFileBytes reads a file the user picked. TriggerDownload pushes a file back to the browser.

Important: You must dot-import pkg/wasm (import . "github.com/felipegenef/gothicframework/v2/pkg/wasm") for use these helpers, otherwise you will get a tinygo compile error.

Note: these calls are blocking. Go's goroutine model handles concurrency for you, so always call them inside a goroutine or a CreateWasmFunc handler.

// Inside CreateWasmFunc — already runs in its own goroutine
 CreateWasmFunc("load", func() {
	 body, err := Fetch("https://api.example.com/data")
	 if err == nil { SetText("result", body) }
})

 // On mount — use go keyword to avoid blocking the main WASM thread
 go func() {
	 body, err := Fetch("https://api.example.com/data")
	 if err == nil { SetText("result", body) }
}() 
// Simple GET, body is returned as string 
 CreateWasmFunc ( "load" ,  func () {
	body, err :=  Fetch ( "https://api.example.com/todos/1" )
	 if  err !=  nil  {
		 SetText ( "result" ,  "error: " +err. Error ())
		 return 
	}
	 SetText ( "result" , body)
}) 

Need more control? Pass a FetchConfig to set method, headers, body, or query parameters.

CreateWasmFunc ( "submit" ,  func () {
	body, err :=  Fetch ( "https://api.example.com/todos" ,  FetchConfig {
		Method:   "POST" ,
		Headers:  map [ string ] string { "Content-Type" :  "application/json" },
		Body:     `{"title":"buy milk"}` ,
	})
	 if  err !=  nil  {  return  }
	 SetText ( "result" , body)
}) 

To handle uploads, read the user's selected file with GetFileBytes and send the []byte through BodyBytes.

// <input type="file" id="upload" /> 
 CreateWasmFunc ( "uploadFile" ,  func () {
	data :=  GetFileBytes ( "upload" )
	 if  data ==  nil  {
		 SetText ( "status" ,  "no file selected" )
		 return 
	}
	_, err :=  Fetch ( "/api/upload" ,  FetchConfig {
		Method:     "POST" ,
		Headers:    map [ string ] string { "Content-Type" :  "application/octet-stream" },
		BodyBytes: data,
	})
	 if  err !=  nil  {
		 SetText ( "status" ,  "upload failed" )
		 return 
	}
	 SetText ( "status" ,  "uploaded!" )
}) 

Going the other way? FetchBytes downloads binary data, and TriggerDownload hands it to the user's browser as a file.

CreateWasmFunc ( "downloadReport" ,  func () {
	data, err :=  FetchBytes ( "/api/report.csv" )
	 if  err !=  nil  {  return  }
	 TriggerDownload ( "report.csv" , data,  "text/csv" )
}) 

Need multiple WASM components to share state and react to each other? Check out Topics next!