routes.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/fs"
  9. "log"
  10. "net"
  11. "net/http"
  12. "os"
  13. "os/signal"
  14. "path/filepath"
  15. "reflect"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "syscall"
  21. "time"
  22. "github.com/gin-contrib/cors"
  23. "github.com/gin-gonic/gin"
  24. "github.com/jmorganca/ollama/api"
  25. "github.com/jmorganca/ollama/llm"
  26. "github.com/jmorganca/ollama/version"
  27. )
  28. var mode string = gin.DebugMode
  29. func init() {
  30. switch mode {
  31. case gin.DebugMode:
  32. case gin.ReleaseMode:
  33. case gin.TestMode:
  34. default:
  35. mode = gin.DebugMode
  36. }
  37. gin.SetMode(mode)
  38. }
  39. var loaded struct {
  40. mu sync.Mutex
  41. runner llm.LLM
  42. expireAt time.Time
  43. expireTimer *time.Timer
  44. *Model
  45. *api.Options
  46. }
  47. var defaultSessionDuration = 5 * time.Minute
  48. // load a model into memory if it is not already loaded, it is up to the caller to lock loaded.mu before calling this function
  49. func load(ctx context.Context, workDir string, model *Model, reqOpts map[string]interface{}, sessionDuration time.Duration) error {
  50. opts := api.DefaultOptions()
  51. if err := opts.FromMap(model.Options); err != nil {
  52. log.Printf("could not load model options: %v", err)
  53. return err
  54. }
  55. if err := opts.FromMap(reqOpts); err != nil {
  56. return err
  57. }
  58. // check if the loaded model is still running in a subprocess, in case something unexpected happened
  59. if loaded.runner != nil {
  60. if err := loaded.runner.Ping(ctx); err != nil {
  61. log.Print("loaded llm process not responding, closing now")
  62. // the subprocess is no longer running, so close it
  63. loaded.runner.Close()
  64. loaded.runner = nil
  65. loaded.Model = nil
  66. loaded.Options = nil
  67. }
  68. }
  69. needLoad := loaded.runner == nil || // is there a model loaded?
  70. loaded.ModelPath != model.ModelPath || // has the base model changed?
  71. !reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
  72. !reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?
  73. if needLoad {
  74. if loaded.runner != nil {
  75. log.Println("changing loaded model")
  76. loaded.runner.Close()
  77. loaded.runner = nil
  78. loaded.Model = nil
  79. loaded.Options = nil
  80. }
  81. llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, opts)
  82. if err != nil {
  83. return err
  84. }
  85. loaded.Model = model
  86. loaded.runner = llmRunner
  87. loaded.Options = &opts
  88. }
  89. loaded.expireAt = time.Now().Add(sessionDuration)
  90. if loaded.expireTimer == nil {
  91. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  92. loaded.mu.Lock()
  93. defer loaded.mu.Unlock()
  94. if time.Now().Before(loaded.expireAt) {
  95. return
  96. }
  97. if loaded.runner != nil {
  98. loaded.runner.Close()
  99. }
  100. loaded.runner = nil
  101. loaded.Model = nil
  102. loaded.Options = nil
  103. })
  104. }
  105. loaded.expireTimer.Reset(sessionDuration)
  106. return nil
  107. }
  108. func GenerateHandler(c *gin.Context) {
  109. loaded.mu.Lock()
  110. defer loaded.mu.Unlock()
  111. checkpointStart := time.Now()
  112. var req api.GenerateRequest
  113. err := c.ShouldBindJSON(&req)
  114. switch {
  115. case errors.Is(err, io.EOF):
  116. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  117. return
  118. case err != nil:
  119. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  120. return
  121. }
  122. if req.Model == "" {
  123. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  124. return
  125. }
  126. model, err := GetModel(req.Model)
  127. if err != nil {
  128. var pErr *fs.PathError
  129. if errors.As(err, &pErr) {
  130. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  131. return
  132. }
  133. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  134. return
  135. }
  136. workDir := c.GetString("workDir")
  137. // TODO: set this duration from the request if specified
  138. sessionDuration := defaultSessionDuration
  139. if err := load(c.Request.Context(), workDir, model, req.Options, sessionDuration); err != nil {
  140. if errors.Is(err, api.ErrInvalidOpts) {
  141. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  142. return
  143. }
  144. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  145. return
  146. }
  147. checkpointLoaded := time.Now()
  148. prompt, err := model.Prompt(req)
  149. if err != nil {
  150. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  151. return
  152. }
  153. ch := make(chan any)
  154. go func() {
  155. defer close(ch)
  156. // an empty request loads the model
  157. if req.Prompt == "" && req.Template == "" && req.System == "" {
  158. ch <- api.GenerateResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true}
  159. return
  160. }
  161. fn := func(r api.GenerateResponse) {
  162. loaded.expireAt = time.Now().Add(sessionDuration)
  163. loaded.expireTimer.Reset(sessionDuration)
  164. r.Model = req.Model
  165. r.CreatedAt = time.Now().UTC()
  166. if r.Done {
  167. r.TotalDuration = time.Since(checkpointStart)
  168. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  169. }
  170. ch <- r
  171. }
  172. if err := loaded.runner.Predict(c.Request.Context(), req.Context, prompt, fn); err != nil {
  173. ch <- gin.H{"error": err.Error()}
  174. }
  175. }()
  176. if req.Stream != nil && !*req.Stream {
  177. var response api.GenerateResponse
  178. generated := ""
  179. for resp := range ch {
  180. if r, ok := resp.(api.GenerateResponse); ok {
  181. generated += r.Response
  182. response = r
  183. } else {
  184. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  185. return
  186. }
  187. }
  188. response.Response = generated
  189. c.JSON(http.StatusOK, response)
  190. return
  191. }
  192. streamResponse(c, ch)
  193. }
  194. func EmbeddingHandler(c *gin.Context) {
  195. loaded.mu.Lock()
  196. defer loaded.mu.Unlock()
  197. var req api.EmbeddingRequest
  198. err := c.ShouldBindJSON(&req)
  199. switch {
  200. case errors.Is(err, io.EOF):
  201. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  202. return
  203. case err != nil:
  204. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  205. return
  206. }
  207. if req.Model == "" {
  208. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  209. return
  210. }
  211. model, err := GetModel(req.Model)
  212. if err != nil {
  213. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  214. return
  215. }
  216. workDir := c.GetString("workDir")
  217. if err := load(c.Request.Context(), workDir, model, req.Options, 5*time.Minute); err != nil {
  218. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  219. return
  220. }
  221. if !loaded.Options.EmbeddingOnly {
  222. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  223. return
  224. }
  225. embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
  226. if err != nil {
  227. log.Printf("embedding generation failed: %v", err)
  228. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  229. return
  230. }
  231. resp := api.EmbeddingResponse{
  232. Embedding: embedding,
  233. }
  234. c.JSON(http.StatusOK, resp)
  235. }
  236. func PullModelHandler(c *gin.Context) {
  237. var req api.PullRequest
  238. err := c.ShouldBindJSON(&req)
  239. switch {
  240. case errors.Is(err, io.EOF):
  241. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  242. return
  243. case err != nil:
  244. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  245. return
  246. }
  247. if req.Name == "" {
  248. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  249. return
  250. }
  251. ch := make(chan any)
  252. go func() {
  253. defer close(ch)
  254. fn := func(r api.ProgressResponse) {
  255. ch <- r
  256. }
  257. regOpts := &RegistryOptions{
  258. Insecure: req.Insecure,
  259. }
  260. ctx, cancel := context.WithCancel(c.Request.Context())
  261. defer cancel()
  262. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  263. ch <- gin.H{"error": err.Error()}
  264. }
  265. }()
  266. if req.Stream != nil && !*req.Stream {
  267. waitForStream(c, ch)
  268. return
  269. }
  270. streamResponse(c, ch)
  271. }
  272. func PushModelHandler(c *gin.Context) {
  273. var req api.PushRequest
  274. err := c.ShouldBindJSON(&req)
  275. switch {
  276. case errors.Is(err, io.EOF):
  277. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  278. return
  279. case err != nil:
  280. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  281. return
  282. }
  283. if req.Name == "" {
  284. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  285. return
  286. }
  287. ch := make(chan any)
  288. go func() {
  289. defer close(ch)
  290. fn := func(r api.ProgressResponse) {
  291. ch <- r
  292. }
  293. regOpts := &RegistryOptions{
  294. Insecure: req.Insecure,
  295. }
  296. ctx := context.Background()
  297. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  298. ch <- gin.H{"error": err.Error()}
  299. }
  300. }()
  301. if req.Stream != nil && !*req.Stream {
  302. waitForStream(c, ch)
  303. return
  304. }
  305. streamResponse(c, ch)
  306. }
  307. func CreateModelHandler(c *gin.Context) {
  308. var req api.CreateRequest
  309. err := c.ShouldBindJSON(&req)
  310. switch {
  311. case errors.Is(err, io.EOF):
  312. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  313. return
  314. case err != nil:
  315. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  316. return
  317. }
  318. if req.Name == "" || req.Path == "" {
  319. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name and path are required"})
  320. return
  321. }
  322. ch := make(chan any)
  323. go func() {
  324. defer close(ch)
  325. fn := func(resp api.ProgressResponse) {
  326. ch <- resp
  327. }
  328. ctx, cancel := context.WithCancel(c.Request.Context())
  329. defer cancel()
  330. if err := CreateModel(ctx, req.Name, req.Path, fn); err != nil {
  331. ch <- gin.H{"error": err.Error()}
  332. }
  333. }()
  334. if req.Stream != nil && !*req.Stream {
  335. waitForStream(c, ch)
  336. return
  337. }
  338. streamResponse(c, ch)
  339. }
  340. func DeleteModelHandler(c *gin.Context) {
  341. var req api.DeleteRequest
  342. err := c.ShouldBindJSON(&req)
  343. switch {
  344. case errors.Is(err, io.EOF):
  345. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  346. return
  347. case err != nil:
  348. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  349. return
  350. }
  351. if req.Name == "" {
  352. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  353. return
  354. }
  355. if err := DeleteModel(req.Name); err != nil {
  356. if os.IsNotExist(err) {
  357. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  358. } else {
  359. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  360. }
  361. return
  362. }
  363. manifestsPath, err := GetManifestPath()
  364. if err != nil {
  365. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  366. return
  367. }
  368. if err := PruneDirectory(manifestsPath); err != nil {
  369. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  370. return
  371. }
  372. c.JSON(http.StatusOK, nil)
  373. }
  374. func ShowModelHandler(c *gin.Context) {
  375. var req api.ShowRequest
  376. err := c.ShouldBindJSON(&req)
  377. switch {
  378. case errors.Is(err, io.EOF):
  379. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  380. return
  381. case err != nil:
  382. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  383. return
  384. }
  385. if req.Name == "" {
  386. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  387. return
  388. }
  389. resp, err := GetModelInfo(req.Name)
  390. if err != nil {
  391. if os.IsNotExist(err) {
  392. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  393. } else {
  394. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  395. }
  396. return
  397. }
  398. c.JSON(http.StatusOK, resp)
  399. }
  400. func GetModelInfo(name string) (*api.ShowResponse, error) {
  401. model, err := GetModel(name)
  402. if err != nil {
  403. return nil, err
  404. }
  405. resp := &api.ShowResponse{
  406. License: strings.Join(model.License, "\n"),
  407. System: model.System,
  408. Template: model.Template,
  409. }
  410. mf, err := ShowModelfile(model)
  411. if err != nil {
  412. return nil, err
  413. }
  414. resp.Modelfile = mf
  415. var params []string
  416. cs := 30
  417. for k, v := range model.Options {
  418. switch val := v.(type) {
  419. case string:
  420. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  421. case int:
  422. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  423. case float64:
  424. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  425. case bool:
  426. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  427. case []interface{}:
  428. for _, nv := range val {
  429. switch nval := nv.(type) {
  430. case string:
  431. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  432. case int:
  433. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  434. case float64:
  435. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  436. case bool:
  437. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  438. }
  439. }
  440. }
  441. }
  442. resp.Parameters = strings.Join(params, "\n")
  443. return resp, nil
  444. }
  445. func ListModelsHandler(c *gin.Context) {
  446. models := make([]api.ModelResponse, 0)
  447. fp, err := GetManifestPath()
  448. if err != nil {
  449. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  450. return
  451. }
  452. walkFunc := func(path string, info os.FileInfo, _ error) error {
  453. if !info.IsDir() {
  454. dir, file := filepath.Split(path)
  455. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  456. tag := strings.Join([]string{dir, file}, ":")
  457. mp := ParseModelPath(tag)
  458. manifest, digest, err := GetManifest(mp)
  459. if err != nil {
  460. log.Printf("skipping file: %s", fp)
  461. return nil
  462. }
  463. models = append(models, api.ModelResponse{
  464. Name: mp.GetShortTagname(),
  465. Size: manifest.GetTotalSize(),
  466. Digest: digest,
  467. ModifiedAt: info.ModTime(),
  468. })
  469. }
  470. return nil
  471. }
  472. if err := filepath.Walk(fp, walkFunc); err != nil {
  473. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  474. return
  475. }
  476. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  477. }
  478. func CopyModelHandler(c *gin.Context) {
  479. var req api.CopyRequest
  480. err := c.ShouldBindJSON(&req)
  481. switch {
  482. case errors.Is(err, io.EOF):
  483. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  484. return
  485. case err != nil:
  486. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  487. return
  488. }
  489. if req.Source == "" || req.Destination == "" {
  490. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  491. return
  492. }
  493. if err := CopyModel(req.Source, req.Destination); err != nil {
  494. if os.IsNotExist(err) {
  495. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  496. } else {
  497. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  498. }
  499. return
  500. }
  501. }
  502. var defaultAllowOrigins = []string{
  503. "localhost",
  504. "127.0.0.1",
  505. "0.0.0.0",
  506. }
  507. func Serve(ln net.Listener, allowOrigins []string) error {
  508. config := cors.DefaultConfig()
  509. config.AllowWildcard = true
  510. config.AllowOrigins = allowOrigins
  511. for _, allowOrigin := range defaultAllowOrigins {
  512. config.AllowOrigins = append(config.AllowOrigins,
  513. fmt.Sprintf("http://%s", allowOrigin),
  514. fmt.Sprintf("https://%s", allowOrigin),
  515. fmt.Sprintf("http://%s:*", allowOrigin),
  516. fmt.Sprintf("https://%s:*", allowOrigin),
  517. )
  518. }
  519. workDir, err := os.MkdirTemp("", "ollama")
  520. if err != nil {
  521. return err
  522. }
  523. defer os.RemoveAll(workDir)
  524. r := gin.Default()
  525. r.Use(
  526. cors.New(config),
  527. func(c *gin.Context) {
  528. c.Set("workDir", workDir)
  529. c.Next()
  530. },
  531. )
  532. r.POST("/api/pull", PullModelHandler)
  533. r.POST("/api/generate", GenerateHandler)
  534. r.POST("/api/embeddings", EmbeddingHandler)
  535. r.POST("/api/create", CreateModelHandler)
  536. r.POST("/api/push", PushModelHandler)
  537. r.POST("/api/copy", CopyModelHandler)
  538. r.DELETE("/api/delete", DeleteModelHandler)
  539. r.POST("/api/show", ShowModelHandler)
  540. for _, method := range []string{http.MethodGet, http.MethodHead} {
  541. r.Handle(method, "/", func(c *gin.Context) {
  542. c.String(http.StatusOK, "Ollama is running")
  543. })
  544. r.Handle(method, "/api/tags", ListModelsHandler)
  545. }
  546. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  547. s := &http.Server{
  548. Handler: r,
  549. }
  550. // listen for a ctrl+c and stop any loaded llm
  551. signals := make(chan os.Signal, 1)
  552. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  553. go func() {
  554. <-signals
  555. if loaded.runner != nil {
  556. loaded.runner.Close()
  557. }
  558. os.RemoveAll(workDir)
  559. os.Exit(0)
  560. }()
  561. if runtime.GOOS == "linux" {
  562. // check compatibility to log warnings
  563. if _, err := llm.CheckVRAM(); err != nil {
  564. log.Printf("Warning: GPU support may not enabled, check you have installed install GPU drivers: %v", err)
  565. }
  566. }
  567. return s.Serve(ln)
  568. }
  569. func waitForStream(c *gin.Context, ch chan interface{}) {
  570. c.Header("Content-Type", "application/json")
  571. for resp := range ch {
  572. switch r := resp.(type) {
  573. case api.ProgressResponse:
  574. if r.Status == "success" {
  575. c.JSON(http.StatusOK, r)
  576. return
  577. }
  578. case gin.H:
  579. if errorMsg, ok := r["error"].(string); ok {
  580. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  581. return
  582. } else {
  583. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  584. return
  585. }
  586. default:
  587. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  588. return
  589. }
  590. }
  591. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  592. }
  593. func streamResponse(c *gin.Context, ch chan any) {
  594. c.Header("Content-Type", "application/x-ndjson")
  595. c.Stream(func(w io.Writer) bool {
  596. val, ok := <-ch
  597. if !ok {
  598. return false
  599. }
  600. bts, err := json.Marshal(val)
  601. if err != nil {
  602. log.Printf("streamResponse: json.Marshal failed with %s", err)
  603. return false
  604. }
  605. // Delineate chunks with new-line delimiter
  606. bts = append(bts, '\n')
  607. if _, err := w.Write(bts); err != nil {
  608. log.Printf("streamResponse: w.Write failed with %s", err)
  609. return false
  610. }
  611. return true
  612. })
  613. }